package com.atguigu.chapter11;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

import java.text.DecimalFormat;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/4/13 16:18
 */
public class Flink13_Function_Agg {
    public static void main(String[] args) {
        
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        DataStreamSource<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 2000L, 20),
                             new WaterSensor("sensor_2", 3000L, 30),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50),
                             new WaterSensor("sensor_2", 6000L, 60));
        
        Table table = tEnv.fromDataStream(waterSensorStream);
        
        // 内联
        /*table
            .groupBy($("id"))
            .select($("id"), call(MyAvg.class, $("vc")).as("vc_sum"))
            .execute()
            .print();*/
        
        // 先注册再使用
        tEnv.createTemporaryFunction("my_avg", MyAvg.class);
        table
            .groupBy($("id"))
            .select($("id"), call("my_avg", $("vc")).as("vc_sum"))
            .execute()
            .print();
        
    }
    
    public static class AvgAcc {
        public Integer sum = 0;
        public Long count = 0L;
    }
    
    public static class MyAvg extends AggregateFunction<Double, AvgAcc> {
        
        // 返回最终聚合的结果
        @Override
        public Double getValue(AvgAcc acc) {
            if (acc.count == 0) return 0D;
            DecimalFormat df = new DecimalFormat("0.00");
            
            return Double.valueOf(df.format(acc.sum * 1.0 / acc.count));
        }
        
        // 创建累加器, 对累计器做初始化
        @Override
        public AvgAcc createAccumulator() {
            return new AvgAcc();
        }
        
        // 对传入的数据进行聚合  avg(vc, 10)
        // 参数1: 累计器
        // 参数2,3,4.. : 传给聚合函数的参数
        public void accumulate(AvgAcc acc, Integer vc) {
            if (vc != null) {
                acc.sum += vc;
                acc.count += 1L;
            }
        }
        
    }
    
}


